package com.cyurs.netty.protocoltcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;
import java.util.UUID;

/**
 * @Author: Cyrus
 * @CreateDate: 2020/11/27
 */
public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    int count;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        //接收到数据进行处理
        int len = msg.getLen();
        byte[] content = msg.getContent();
        System.out.println("接收到服务器的消息：");
        System.out.println("长度=" + len);
        System.out.println("内容=" + new String(content, Charset.forName("utf-8")));
        System.out.println("服务器接收到消息包数量="+(++this.count));

        //回复消息
        String responseContent = UUID.randomUUID().toString();
        byte[] content1 = responseContent.getBytes(Charset.forName("utf-8"));
        int len1 = responseContent.getBytes(Charset.forName("utf-8")).length;
        //构建一个协议包
        MessageProtocol messageProtocol = new MessageProtocol();
        messageProtocol.setLen(len1);
        messageProtocol.setContent(content1);
        ctx.writeAndFlush(messageProtocol);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
